package nl.maarten.docenthelp.gui;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import nl.maarten.docenthelp.entity.UserType;
import nl.maarten.docenthelp.manager.LoginManager;
import nl.maarten.docenthelp.util.Util;

public class LoginWindow extends JFrame implements ActionListener
{
	private static final long serialVersionUID = -7300681796408797952L;
	
	//breedte en hoogte van de window
	private static final int[] WINDOW_SIZE = { 400, 400 };
	
	//titel van de window
	private static final String WINDOW_TITLE = "Login";
	
	private JLabel lblUsername;
	private JLabel lblPassword;
	
	private JTextField txtUsernamer;
	
	private JPasswordField txtPassword;
	
	private JButton btnLogin;
	
	//constructor
	public LoginWindow()
	{
		init();
	}
	
	private void init()
	{
		setTitle(WINDOW_TITLE);
		setSize(WINDOW_SIZE[0], WINDOW_SIZE[1]);
		setPreferredSize(new Dimension(WINDOW_SIZE[0], WINDOW_SIZE[1]));
		setLocationRelativeTo(null);
		setResizable(false); //mag het venster worden geresized???
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setLayout(null);
		
		lblUsername = new JLabel();
		lblUsername.setText("Gebruikersnaam");
		lblUsername.setSize(150, 20);
		lblUsername.setLocation(20, 20);
		
		add(lblUsername);
		
		lblPassword = new JLabel();
		lblPassword.setText("Wachtwoord");
		lblPassword.setSize(150, 20);
		lblPassword.setLocation(20, 45);
		
		add(lblPassword);
		
		txtUsernamer = new JTextField();
		txtUsernamer.setSize(150, 20);
		txtUsernamer.setLocation(175, 20);
		
		add(txtUsernamer);
		
		txtPassword = new JPasswordField();
		txtPassword.setSize(150, 20);
		txtPassword.setLocation(175, 45);
		
		add(txtPassword);
		
		btnLogin = new JButton();
		btnLogin.setText("Login");
		btnLogin.setSize(75, 20);
		btnLogin.setLocation(250, 70);
		btnLogin.addActionListener(this);
		
		add(btnLogin);
						
		setVisible(true);
		pack();
	}

	@Override
	public void actionPerformed(ActionEvent e)
	{
		if (e.getSource() == btnLogin)
		{
			String pass = Util.MD5(new String (txtPassword.getPassword()));
			
			if(LoginManager.getInstance().login(txtUsernamer.getText(), pass) != null)
			{
				if(LoginManager.getInstance().getCurrentUser().getType() == UserType.TEACHER)
				{
					setVisible(false);
					new MainWindow();
				}
				else
				{
					JOptionPane.showMessageDialog(null, "Geen docent recht gevonden.");
				}
			}
		}
	}
}
